package tw.com.hitevision.whiteboard.android.util;

import android.text.TextUtils;
import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by ghl
 */
public class HttpShareUtils {

    /**
     * 获取生成二维码url
     * @param cosPath
     * @return
     */
    public static String httpRequest(String cosPath,int page) {
        HttpClient httpCient = new DefaultHttpClient();
        httpCient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,5000);//连接时间
        Map<String, String> params = new TreeMap();
        long timestamp = System.currentTimeMillis() / 1000;
        String md5File = md5(System.currentTimeMillis()+"");
        try {
            params.put("appname", URLEncoder.encode("\u5546\u52a1\u5927\u5c4f", HTTP.UTF_8));
            params.put("resttime", URLEncoder.encode(timestamp+"", HTTP.UTF_8));
            params.put("file_guid", URLEncoder.encode(md5File, HTTP.UTF_8));
            params.put("file_title", URLEncoder.encode("\u4f1a\u8bae\u8bb0\u5f55", HTTP.UTF_8));
            params.put("file_desc", URLEncoder.encode("\u5206\u4eab\u63cf\u8ff0", HTTP.UTF_8));
            params.put("file_path", URLEncoder.encode("/" + cosPath + "/", HTTP.UTF_8));
            params.put("file_pages", URLEncoder.encode(String.valueOf(page), HTTP.UTF_8));
            params.put("file_pass", URLEncoder.encode("password", HTTP.UTF_8));
            params.put("file_count", URLEncoder.encode("0", HTTP.UTF_8));
            params.put("file_time", URLEncoder.encode(timestamp+"", HTTP.UTF_8));
            params.put("uid", URLEncoder.encode("0", HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String restauth =  md5(buildParams(params) + "&" + "cf3aa39819d2856a4419be99ce559ca2");
        StringBuilder builder = new StringBuilder("http://www.hitecloud.net:8200/api/fileshare/savefile");
        builder.append("?");
        try {
            builder.append("appname=" + URLEncoder.encode("\u5546\u52a1\u5927\u5c4f", HTTP.UTF_8) + "&");
            builder.append("resttime=" + timestamp + "&");
            builder.append("restauth=" + restauth + "&");
            builder.append("file_guid=" + md5File + "&");
            builder.append("file_title=" + URLEncoder.encode("\u4f1a\u8bae\u8bb0\u5f55", HTTP.UTF_8) + "&");
            builder.append("file_desc=" + URLEncoder.encode("\u5206\u4eab\u63cf\u8ff0", HTTP.UTF_8) + "&");
            builder.append("file_path=/" + cosPath + "/" + "&");
            builder.append("file_pages=" + page + "&");
            builder.append("file_pass=password&");
            builder.append("file_count=0&");
            builder.append("file_time=" + timestamp + "&");
            builder.append("uid=0");
        } catch (UnsupportedEncodingException e2) {
            e2.printStackTrace();
        }
        HttpGet httpGet = new HttpGet(builder.toString());
        try {
            HttpResponse httpResponse = httpCient.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode() != 200){
                return "error";
            }
            String response = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
            JSONObject jsonObject = new JSONObject(response);
            String url = jsonObject.optString("data");
            if (!TextUtils.isEmpty(url) && !"null".equals(url)){
                return url;
            }else {
                return "";
            }
        } catch (JSONException e){
            e.printStackTrace();
        } catch (Exception e3) {
            Log.e("HttpShareUtils","exception = "+e3);
            e3.printStackTrace();
        }
        return "error";
    }

    public static String getMD5(byte[] source) {
        String s = null;
        char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(source);
            byte[] tmp = md.digest();
            char[] str = new char[32];
            int k = 0;

            for(int i = 0; i < 16; ++i) {
                byte byte0 = tmp[i];
                str[k++] = hexDigits[byte0 >>> 4 & 15];
                str[k++] = hexDigits[byte0 & 15];
            }

            s = new String(str);
        } catch (Exception var9) {
            var9.printStackTrace();
        }

        return s;
    }

    public static String md5(String string)
    {
        if (TextUtils.isEmpty(string))
        {
            return "";
        }
        try
        {
            byte[] bytes = MessageDigest.getInstance("MD5").digest(string.getBytes());
            String result = "";
            for (byte b : bytes)
            {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1)
                {
                    temp = "0" + temp;
                }
                result = new StringBuilder(String.valueOf(result)).append(temp).toString();
            }
            return result;
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
            return "";
        }
    }

    public static String buildParams(Map<String, String> map) {
        StringBuilder builder = new StringBuilder();
        for (String key : map.keySet()) {
            builder.append(new StringBuilder(String.valueOf(key)).append("=").append((String) map.get(key)).append("&")
                    .toString());
        }
        builder.deleteCharAt(builder.length() - 1);
        return builder.toString();
    }

}
